import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { ProCard } from '@ant-design/pro-components';
import { Row, Button, Modal, Form, Select, Radio, Col, Upload, Input, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { connect, useDispatch } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import { request } from '@/utils/request';
const FormItem = Form.Item;
const Option = Select.Option;

//定义通知标题样式
const titleStyle = {
  fontWeight: 'bolder',
  fontSize: '20px',
  color: 'black',
};
//定义通知内容样式
const contentStyle = {
  whiteSpace: 'pre-wrap',
  textAlign: 'left',
  fontSize: '16px',
  lineHeight: '1.5',
};

function NotificationDetail() {
  const [result, setResult] = useState({});
  const dispatch = useDispatch();
  const location = useLocation();
  //上传回执弹窗的可见性和弹窗中应该渲染的内容
  const [isModalVisible, setIsModalVisible] = useState(false);

  //获取通知详情的具体参数
  const searchParams = new URLSearchParams(location.search);
  const notificationId = searchParams.get('id');
  console.log(notificationId)
  const studentCode = searchParams.get('stuCode');
  const [formtype,setformtype]= useState({});

  const [formdata] = Form.useForm();
  const [file, setFile] = useState();

  const handleSubmit = () => {
    formdata
      .validateFields() // 手动触发表单项的校验
      .then((values) => {
        // console.log('上传的文件：', file);
        const formData = new FormData();
        formData.append('id', notificationId);
        formData.append('stuCode', studentCode);
        formData.append('uploadfile', file);

        formData.append('form', JSON.stringify({"title":formtype.title,"value":values.content}));
        console.log(file);

        request('/api/freshSystem/student/receiptAttachedFile', {
          method: 'POST',
          body: formData
        }).then((response: any)=>{
          if (response.code == 200 && response.result == true){
            message.success("提交成功")
            handleModalClose();
          }
        })
      })
      .catch((error) => {
        // 校验失败处理
        console.error('表单校验失败:', error);
      });
  };

  const normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  //获取通知详情数据
  useEffect(() => {
    dispatch({
      type: 'Model_noticeforstuModel/getNoticeDetailEffects',
      payload: {
        // code: JSON.parse(props.user.currrentuser).account,
        code: { id: notificationId, stuCode: studentCode },
        callback: (value: any) => {
          setResult(value);
          setformtype(JSON.parse(value.form))
          // console.log(value);
        },
      },
    });
  }, [notificationId, studentCode, dispatch]);

  // 处理附件下载
  const handleDownloadAttachment = () => {
    window.open(`/api/freshSystem/downloadFile/${result.fileId}`)
  };

  // 处理上传回执
  const handleUploadReceipt = () => {
    setIsModalVisible(true); // 显示弹窗
    handleResetForm();
  };

  // 处理关闭弹窗
  const handleModalClose = () => {
    setIsModalVisible(false);
  };

  //用户输入重置
  const handleResetForm = () => {
    formdata.resetFields();
    setFile([]); // 清空上传文件列表
  };

  // 检查result是否为空或未定义
  if (!result || Object.keys(result).length === 0) {
    return <div>正在努力加载中...</div>; // 渲染一个加载信息或旋转图标
  }

  return (
    <PageContainer>
      <div>
        <ProCard headerBordered>
          <ProCard title={<span style={titleStyle}>{`主题：${result.title}`}</span>} headerBordered>
            <Row justify="center">
              <Col span={20}>
                <pre style={contentStyle} dangerouslySetInnerHTML={{ __html: result.content }} />
                <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '20px' }}>
                  {result.fileId && (
                    <Button
                      style={{ marginRight: '10px' }}
                      type="primary"
                      onClick={handleDownloadAttachment}
                    >
                      下载附件
                    </Button>
                  )}
                  {(result.isFile === 1 || result.isForm === 1) && (
                    <Button type="primary" onClick={handleUploadReceipt}>
                      上传回执
                    </Button>
                  )}

                </div>
              </Col>
            </Row>
          </ProCard>
        </ProCard>
        <Modal
          title="上传回执"
          visible={isModalVisible}
          onCancel={handleModalClose}
          width={1000}
          footer={null} // 将 footer 设为 null，隐藏确认和取消按钮
        >
          <Form layout="horizontal" onFinish={handleSubmit} form={formdata}>

            {(formtype.type === "1") && (
              <FormItem
                label={formtype.title}
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                required
                name="content"
              >
                <Select style={{ width: 200 }}>
                  {formtype.option?.map((option, index) => (
                    <Option key={index} value={option.optionName}>
                      {option.optionName}
                    </Option>
                  ))}
                </Select>
              </FormItem>
             )}

            {(formtype.type === "0") && (
              <Form.Item
                label={formtype.title}
                labelCol={{ span: 8 }}
                name="content"
                rules={[{ required: true, }]}
              >
                <Input />
              </Form.Item>
            )}

            <FormItem
              label="请选择要上传的文件:"
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              help="仅支持上传一个文件"
              name="upload"
              valuePropName="fileList"
              getValueFromEvent={normFile}
            >
              <Upload
                name="logo"
                customRequest={({ file, onSuccess, onError }) => {
                  setFile(file)
                  onSuccess('文件选择成功');
                }}
                listType="picture"
                multiple={false}
                // maxCount={1}
              >
                <Button type="ghost">
                  <UploadOutlined /> 点击上传
                </Button>
              </Upload>
            </FormItem>

            <FormItem wrapperCol={{ span: 24 }} style={{ textAlign: 'right' }}>

              <Button type="default" style={{ marginRight: 10 }} onClick={handleResetForm}>
                清空表单
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </FormItem>
          </Form>
        </Modal>
      </div>
    </PageContainer>
  );
}

export default connect(({ Model_noticeforstuModel }: any) => ({
  Model_noticeforstuModel,
}))(NotificationDetail);
